//  OcenController.swift
//  PoomsaeScringAll
//
//  Created by Илья Проскурнев on 12/02/2019.
//  Copyright © 2019 Илья Проскурнев. All rights reserved.

import UIKit
import AVFoundation
import AudioToolbox

class OcenController: UIViewController {
    
    @IBOutlet var swipeOcen: UIView!
    @IBOutlet weak var loadVist: UIActivityIndicatorView!
    
    var idhost: String?
    var phumseName: String?
    var sudNum: Int?
    var kolSud: Int?
    var sys: Int!
    var kort: Int?
    
    var URL_VISTUP: String?
    let URL_VISTUPLENIE2 = "/php_isap/vistup/vistuplenie.php"
    
    var URL_SUD: String?
    let URL_SUD2 = "/php_isap/sud/sudi.php"
    
    var URL_SUDGOT: String?
    let URL_SUDGOT2 = "/php_isap/sud/sudigotov.php"
    
    @IBOutlet weak var sudNomer: UILabel!
    @IBOutlet weak var phumse: UILabel!
    
    var vistocen: Int!
    
    var idvistuplenie: Int?
    var success: Int?
    var pokaz: Int?
    
    var pr1: Int!
    var pr2: Int!
    var pr3: Int!
    
    @IBOutlet weak var tempImageView: UIImageView!
    
    @IBOutlet weak var can03: UIButton!
    @IBOutlet weak var res: UIButton!
    @IBOutlet weak var can01: UIButton!
    @IBOutlet weak var err01: UILabel!
    @IBOutlet weak var err03: UILabel!
    @IBOutlet weak var presentation: UIButton!
    
    @IBOutlet weak var accuracy: UILabel!
    var doubleAccuracy: Double?
    var setAccuracy: Int?
    var num03 = 0
    var num01 = 0
    var Acd = Double(0)
    var line = Double(0)
    
    var gotov = 0
    
    var touchCount: Int!
    
    var toPoint = CGPoint.zero
    var lastPoint = CGPoint.zero
    var green: CGFloat = 0.0
    var brushWidth: CGFloat = 10.0
    var opacity: CGFloat = 1.0
    var swiped = false
    
    func vistuplenieItem() {
            let url: URL = URL(string: self.URL_VISTUP ?? "localhost")!
            print("url = ", url)
            let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
            let task = defaultSession.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print("Failed to download data")
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                        self.vistuplenieItem()
                    })
                }else {
                    self.parseJSONVistup(data!)
                }
            }
            task.resume()
        }
    
        func parseJSONVistup(_ data:Data) {
    
            var jsonResult = NSDictionary()
            do {
                jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                let idvist = jsonResult["success"] as? String
                let kolVist = jsonResult["vistuplenie_pokaz"] as? String
                let phum = jsonResult["phumse"] as? String
                if (idvist != nil) {
                    self.idvistuplenie = Int (idvist!)!
                    self.pokaz = Int (kolVist!)!
                    self.phumseName = String (phum!)
                } else { self.idvistuplenie = 0 }
            } catch {
                print(error)
            }
            if (self.idvistuplenie != 0) {
                sudi()
            } else {
                DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                    self.vistuplenieItem()
                })
            }
        }
    
    @discardableResult
    func printScoring(_: String) -> String {
        
        if(num03 == 0) {
            err03.text = "0 X"
        } else {
            err03.text = String(num03) + " X"
        }
        
        if(num01 == 0) {
            err01.text = "X 0"
        } else {
            err01.text = "X " + String(num01)
        }
        
        let acc = 40 - num01 - (num03 * 3)
        if (acc<0) {
            Acd = 0
        } else {
            Acd = (Double(acc)/Double(10))
        }
        let sc = String(Acd)
        accuracy.text = sc
        return sc
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if (self.gotov == 1) {
            tempImageView.image = nil
            swiped = false
            let koltouch = event?.allTouches
            touchCount = koltouch?.count
            if let touch = touches.first{
                lastPoint = touch.location(in: self.view)
            }
        }
    }
    
    func drawLineFrom01(fromPoint: CGPoint, toPoint: CGPoint) {
        UIGraphicsBeginImageContext(view.frame.size)
        let context = UIGraphicsGetCurrentContext()
        view.draw(CGRect(x:0, y:0, width: view.frame.size.width, height: view.frame.size.height))
        
        context?.move(to: CGPoint (x:fromPoint.x, y:fromPoint.y))
        context?.addLine(to: CGPoint (x:toPoint.x, y:toPoint.y))
        context?.setLineWidth(10.0)
        context?.setStrokeColor(UIColor.green.cgColor)
        context?.strokePath()
        
        tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        tempImageView.alpha = opacity
        UIGraphicsEndImageContext()
    }
    
    func drawLineFrom03(fromPoint: CGPoint, toPoint: CGPoint) {
        UIGraphicsBeginImageContext(view.frame.size)
        let context = UIGraphicsGetCurrentContext()
        view.draw(CGRect(x:0, y:0, width: view.frame.size.width, height: view.frame.size.height))
        
        context?.move(to: CGPoint (x:fromPoint.x, y:fromPoint.y))
        context?.addLine(to: CGPoint (x:toPoint.x, y:toPoint.y))
        context?.setLineWidth(10.0)
        context?.setStrokeColor(UIColor.red.cgColor)
        context?.strokePath()
        
        tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        tempImageView.alpha = opacity
        UIGraphicsEndImageContext()
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if(self.gotov == 1) {
            swiped = true
            if let touch = touches.first {
                let koltouch = event?.allTouches
                touchCount = koltouch?.count
                toPoint = touch.location(in: view)
                if(touchCount == 1) {
                    drawLineFrom01(fromPoint: lastPoint, toPoint: toPoint)
                }
                if(touchCount == 2) {
                    drawLineFrom03(fromPoint: lastPoint, toPoint: toPoint)
                }
            }
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        if (swiped == true && touchCount == 1 && (lastPoint.x - toPoint.x != 0 || lastPoint.y - toPoint.y != 0)) {
            if (num01+num03*3 < 40) {
                num01 = num01+1
            }
        }
        if (swiped == true && touchCount == 2 && (lastPoint.x - toPoint.x != 0 || lastPoint.y - toPoint.y != 0)) {
            if (num01+num03*3 < 40) {
                num03 = num03+1
            }
        }
        printScoring(String(accuracy.text! as NSString))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.setHidesBackButton(true, animated: true)
        // Do any additional setup after loading the view.
        can03.layer.cornerRadius = 3
        can03.layer.borderWidth = 3
        can03.layer.borderColor = UIColor.gray.cgColor
        
        can01.layer.cornerRadius = 3
        can01.layer.borderWidth = 3
        can01.layer.borderColor = UIColor.gray.cgColor
        
        res.layer.cornerRadius = 3
        res.layer.borderWidth = 3
        res.layer.borderColor = UIColor.gray.cgColor
        
        self.swipeOcen.bringSubviewToFront(self.tempImageView)
        self.swipeOcen.sendSubviewToBack(self.accuracy)
        
        swipeOcen.isHidden = true
        printScoring(String(accuracy.text! as NSString))
        self.URL_VISTUP = self.idhost! + self.URL_VISTUPLENIE2
        self.loadVist.isHidden = false
        self.loadVist.startAnimating()
        vistuplenieItem()
    }
    
    @IBAction func cancel03(_ sender: Any) {
        
        if (num03>0) { num03=num03-1 }
        printScoring(String(accuracy.text! as NSString))
        tempImageView.image = nil
        
    }
    @IBAction func reset(_ sender: Any) {
        
        num01 = 0
        num03 = 0
        printScoring(String(accuracy.text! as NSString))
        tempImageView.image = nil
        
    }
    @IBAction func cancel01(_ sender: Any) {
        
        if (num01>0) { num01=num01-1 }
        printScoring(String(accuracy.text! as NSString))
        tempImageView.image = nil
        
    }
    
    override func prepare (for segue: UIStoryboardSegue, sender: Any?) {
        let presentationController: PresentationController = segue.destination as! PresentationController
        presentationController.idhost = self.idhost
        presentationController.sudNum = self.sudNum
        presentationController.idvistuplenie = self.idvistuplenie!
        presentationController.Acd = self.Acd
        presentationController.num01 = self.num01
        presentationController.num03 = self.num03
        presentationController.kolSud = self.kolSud
        presentationController.pokaz = self.pokaz
        presentationController.sys = self.sys
        presentationController.vistocen = self.vistocen
        presentationController.kort = self.kort
    }
    
    func sudi()  {
        
        self.URL_SUD = self.idhost! + self.URL_SUD2
        let requestURL = NSURL(string: URL_SUD!)
        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: requestURL! as URL)
        //setting the method to post
        request.httpMethod = "POST"
        //creating the post parameter by concatenating the keys and values from text field
        let postParameters = "vistuplenie_idvistuplenie="+String(self.idvistuplenie!)+"&nomersud="+String (self.sudNum!);
        //adding the parameters to request body
        request.httpBody = postParameters.data(using: String.Encoding.utf8)
        var myJSON = NSDictionary()
        //creating a task to send the post request
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in
            //parsing the response
            do {
                if (error != nil) {
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                        self.sudi()
                    })
                } else {
                //converting resonse to NSDictionary
                myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                    self.success = (myJSON["success"] as! Int?)!
                    if (self.success! > 0) {
                        self.sudigotov()
                    }
                }
                
            } catch {
                print(error)
            }
            
        }
        //executing the task
        task.resume()
    }
    
    func sudigotov()  {
        self.URL_SUDGOT = self.idhost! + self.URL_SUDGOT2
        let requestURL = NSURL(string: URL_SUDGOT!)
        //creating NSMutableURLRequest
        let request = NSMutableURLRequest(url: requestURL! as URL)
        //setting the method to post
        request.httpMethod = "POST"
        //creating the post parameter by concatenating the keys and values from text field
        let postParameters = "vistuplenie_idvistuplenie=" + String (self.idvistuplenie!);
        //adding the parameters to request body
        request.httpBody = postParameters.data(using: String.Encoding.utf8)
        var myJSON = NSDictionary()
        //creating a task to send the post request
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            //parsing the response
            do {
                if (error != nil) {
                    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                        self.sudigotov()
                    })
                } else {
                //converting resonse to NSDictionary
                myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                    self.success = (myJSON["success"] as! Int?)!
                    if (self.success != self.kolSud) {
                            DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                                    self.sudigotov()
                            })
                        } else {
                                    
                        DispatchQueue.main.async {
                            self.loadVist.stopAnimating()
                            self.loadVist.isHidden = true
                                self.swipeOcen.isHidden = false
                                self.gotov = 1
                                self.sudNomer.text = "Судья № " + String (self.sudNum!)
                                self.phumse.text = "Пхумсэ " + self.phumseName!
                        }
                    }
                }
            } catch {
                print("Tut error")
            }
            
        }
        //executing the task
        task.resume()
    }
    
    
}
